import asyncio
import orjson
from typing import List
from multiprocess import cpu_count
from concurrent.futures import ThreadPoolExecutor

from loguru import logger
from datetime import datetime

def get_text_content(filename: str) -> str:
    # 读取文件内容
    with open(filename, 'r', encoding='utf-8') as file:
        text = file.read()
        file.close()

    return text

def get_now() -> str:
    return datetime.now().strftime("%m/%d/%Y, %H:%M:%S")

def get_today() -> str:
    return datetime.today().strftime('%Y/%m/%d')

def get_number_of_workers(workers=None):
    if workers == -1 or workers is None:
        workers = (cpu_count() * 2) + 1
    logger.debug(f"Number of workers: {workers}")
    return workers

def init_event_loop(max_workers=3) -> asyncio.AbstractEventLoop:
    """
    Ensure that there is always an event loop available.

    This function tries to get the current event loop. If the current event loop is closed or does not exist,
    it creates a new event loop and sets it as the current event loop.

    Returns:
        asyncio.AbstractEventLoop: The current or newly created event loop.
    """
    executor = ThreadPoolExecutor(max_workers=max_workers)  # Set the number of threads here
    try:
        # Try to get the current event loop
        current_loop = asyncio.get_event_loop()
        if current_loop._closed:
            raise RuntimeError("Event loop is closed.")
        current_loop.set_default_executor(executor)
        return current_loop

    except RuntimeError:
        # If no event loop exists or it is closed, create a new one
        logger.info("Creating a new event loop in main thread.")
        new_loop = asyncio.new_event_loop()
        new_loop.set_default_executor(executor)
        asyncio.set_event_loop(new_loop)

        return new_loop

# Yield successive n-sized
# chunks from l.
def divide_chunks(l, n):
    # looping till length l
    for i in range(0, len(l), n): 
        yield l[i:i + n]    

# Remove backticks for Neo4j compatiable
def _remove_backticks(text: str) -> str:
    return text.replace("`", "")

def _save(records: List[dict], file_path: str) -> None:
    with open(file_path, "wb", buffering=1024*1024*16) as file:
        file.write(orjson.dumps(records))
        file.close()

def _load(file_path: str) -> List[dict]:
    with open(file_path, "rb", buffering=1024*1024*16) as file:
        return orjson.loads(file.read())
